<template>
  <a-card :bordered="false" :loading="loading">
    <DynamicForm
      :data-source="dataColumn"
      :model-data="{ ...detailData, roleId: detailData?.role?.id }"
      @submit-form="submitForm"
      @cancel="closeTab"
    ></DynamicForm>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { categoryApi, createCategory, updateCategory } from '@/api/category';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { categoryTypeList } from '@/enums/categoryTypeEnum';

  const route = useRoute();
  const tabsViewStore = useTabsViewStore();
  const dataColumn = ref([
    {
      field: 'name',
      component: ComponentsTypeEnum.Input,
      label: '分类名称',
      colProps: {
        span: 12,
      },
      rules: [{ required: true }],
    },
    {
      field: 'type',
      component: ComponentsTypeEnum.Select,
      componentProps: {
        options: categoryTypeList,
      },
      label: '类型',
      colProps: {
        span: 12,
      },
      rules: [{ required: true }],
    },
    {
      field: 'sort',
      component: ComponentsTypeEnum.Input,
      label: '排序',
      colProps: {
        span: 12,
      },
      rules: [],
    },
    {
      field: 'remark',
      component: ComponentsTypeEnum.InputTextarea,
      label: '备注',
      colProps: {
        span: 12,
      },
      rules: [],
    },
  ]);
  const { detailData, loading } = useRequestDetail({
    apiKey: categoryApi.categoryDetail,
    initParams: route?.query,
    isMount: !!Object.values(route?.query).length && !!Object.values(route?.query)[0],
  });
  const submitForm = async (params) => {
    const categoryId = route?.query?.id;
    const res = categoryId
      ? await updateCategory({
          ...params,
          id: categoryId,
        })
      : await createCategory(params);
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };
</script>

<style></style>
